﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Soft.Net
{
    /// <summary>
    /// 发送UDP广播
    /// </summary>
    public class UDPBroadcastSend : BaseUDPBroadcast
    {
        public override Result Start()
        {
            Result result = new Result();
            if (base.State == ServerState.Stopped || base.State == ServerState.Error)
            {
                base.State = ServerState.Starting;
                try
                {
                    base.IPEndPoint = new IPEndPoint(IPAddress.Broadcast, base.Port);
                    base.UDPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    base.UDPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                    base.State = ServerState.Started;
                }
                catch (Exception exception)
                {
                    base.State = ServerState.Error;
                    result.AddError(exception, null);
                }
            }
            base.Start();
            return result;
        }


        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public Result Send(byte[] data)
        {
            Result result = new Result();
            if (base.State == ServerState.Started)
            {
                try
                {
                    byte[] array = new byte[(int)base.MaxBufferSize];
                    int length = (data.Length > (int)base.MaxBufferSize) ? ((int)base.MaxBufferSize) : data.Length;
                    Array.Copy(data, array, length);
                    Socket udpsocket = base.UDPSocket;
                    byte[] array2 = array;
                    if (array2 == null)
                    {
                        throw new ArgumentNullException("data");
                    }
                    udpsocket.SendTo(array2, base.IPEndPoint);
                    return result;
                }
                catch (Exception exception)
                {
                    result.AddError(exception, null);
                    return result;
                }
            }
            result.AddError("Socket没有被启动", null);
            return result;
        }
    }
}
